package com.jshoperxms.action.mall.frontstage.interceptors;

import java.io.IOException;
import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.ParentPackage;

import com.jshoperxms.action.mall.backstage.vo.response.ResponseBaseMsg;
import com.jshoperxms.action.utils.json.GsonJson;
import com.jshoperxms.action.utils.statickey.StaticKey;
import com.jshoperxms.entity.MemberT;
import com.jshoperxms.redis.service.RedisBaseTService;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;

@ParentPackage("jshoperxms")
public class ValidateMallSessionInterceptor extends MethodFilterInterceptor{

	@Resource
	private RedisBaseTService<MemberT> redisBaseTService;
	
	private boolean scuflag;
	
	public boolean isScuflag() {
		return scuflag;
	}


	public void setScuflag(boolean scuflag) {
		this.scuflag = scuflag;
	}


	@Override
	protected String doIntercept(ActionInvocation invocation) throws Exception {
		HttpServletRequest request=ServletActionContext.getRequest();
		if(request.getHeader("x-session-token")!=null){
			String token=request.getHeader("x-session-token");
			MemberT basicUser=redisBaseTService.get(token, MemberT.class);
			if(basicUser!=null){
				String rtoken=basicUser.getId();
				if(StringUtils.equalsIgnoreCase(rtoken, token)){
					return invocation.invoke();
				}
			}
		}
		printMsg();
		return null;
	}

	/**
	 * 输出返回信息
	 * @throws IOException
	 */
	private void printMsg() throws IOException{
		ResponseBaseMsg rm=new ResponseBaseMsg();
		rm.setMsg(StaticKey.INVALIDACCESS);
		rm.setSessionTimeOut(true);
		String jsonstr = GsonJson.parseDataToJson(rm);
		PrintWriter out = null;
		HttpServletResponse response = ServletActionContext.getResponse();  
		response.setContentType(StaticKey.CONTENTTYPE);
		response.setCharacterEncoding(StaticKey.ENCODING);
		out = response.getWriter();
		out.write(jsonstr);
	}

}
